import React, { useState, useEffect } from 'react';
import { Form, Row, Input, Pagination, } from 'antd';
import { axconst } from '@/shared/axconst';
import AxModal from '@/components/AxForm/AxModal/index';
import AxTable from '@/components/AxList/AxTable';
import { AxSelectTableProps } from './AxSelectForm';
import AxColumnAction from '@/components/AxList/AxColumnAction';

const { Search } = Input;
/**
 * 自定义选择冲抵
 * @param title 表单名称
 * @param searchField 查询字段（默认值name）
 * @param searchValue 查询内容
 * @param keyField 作为key的字段（如果没有id，需要指定一个）
 * @param placeholder 占位符
 * @param visible 可见性
 * @param autoSelect 当只有一条数据时，自动选中
 * @param showPagination 展示分页（默认true）
 * @param handleVisible 可见性处理函数
 * @param handleRead 选项数据读取函数
 * @param handleCreate 添加处理函数
 */
const AxSelectTable: React.FC<AxSelectTableProps> = props => {
  const {
    searchField = 'name',
    searchValue,
    keyField,
    placeholder = '搜索',
    columns,
    autoSelect = false,
    handleRead: handleReadFromProps,
    handleSelect,
    handleVisible,
    fixOperateButton = true,
    showPagination = true,
    ...rest
  } = props;
  const [data, setData] = useState<any>({
    list: [],
    pagination: {},
    success: false,
  });
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  /** 查询字段 */
  const [field, setField] = useState({});
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  /** 分页初始值 */
  let page = axconst.page.params;

  useEffect(() => {
    if (searchValue && searchValue.trim() !== '') {
      handleSearch(searchValue.trim());
    }
    else setVisible(true);
  }, [searchValue]);

  /** 点击行选中 */
  const handleClickRow = ({ record }: any) => {
    if (handleSelect) handleSelect(record);
    if (handleVisible) handleVisible();
  };

  /** 搜索 */
  const handleSearch = (val: any) => {
    let f = {};
    if (val && val.trim() !== '') {
      f[searchField] = val.trim();
    }
    setField(f);
    return handleRead(f);
  };

  /** 读取数据 */
  const handleRead = (f?: any) => {
    if (handleReadFromProps) {
      setLoading(true);
      f = f || field;
      return handleReadFromProps(page, f).then((res: any) => {
        if (autoSelect === true && res && res.list && res.list.length === 1) {
          handleClickRow({ record: res.list[0] });
        }
        else {
          if (keyField) setData({
            ...res,
            list: res.list.map((i: any) => ({
              ...i,
              id: i[keyField],
            })),
          })
          else
            setData(res);
          setLoading(false);
          setVisible(true);
        }
      });
    }
  };

  /** 改变分页 */
  const handlePageChange = (currentPage: any, pageSize: any) => {
    page = {
      currentPage,
      pageSize,
    };
    handleRead();
  };

  let columnsEx = columns.map((i: any) => i);
  const fixed = fixOperateButton ? { fixed: 'right' } : {};

  columnsEx.push({
    axtype: 'operate',
    title: '操作',
    width: axconst.width.two,
    ...fixed,
    render: (val: any, record: any) => (
      <AxColumnAction
        buttons={[
          {
            text: '选择',
            onClick: () => handleClickRow({ record }),
          }
        ]}
      />
    ),
  });

  return (
    <AxModal
      showLoading={false}
      footer={false}
      width="40%"
      handleVisible={handleVisible}
      {...rest}
      visible={visible}
      items={[
        <Row gutter={24}>
          <Search
            placeholder={placeholder}
            onSearch={val => handleSearch(val)}
            defaultValue={searchValue}
            // style={{ width: '100%' }}
            allowClear
          />
          <AxTable
            bordered
            size="small"
            checkboxModel={false}
            // addemptycolumn={true}
            columns={columnsEx}
            data={data}
            loading={loading}
            scroll={{ x: 'max-content', y: 240 }}
            showPagination={false}
            onRow={(record: any) => ({
              onDoubleClick: () => {
                handleClickRow({ record });
              },
            })}
            onGetFirstData={handleSearch}
            expandedRowKeys={expandedRowKeys}
            onExpandedRowsChange={setExpandedRowKeys}
          />
          {showPagination && <Pagination
            size="small"
            style={{ float: 'right', marginTop: '5px' }}
            pageSize={page.pageSize}
            total={data.pagination.total}
            onChange={handlePageChange}
          />}
        </Row>,
      ]}
    />
  );
};

export default Form.create<any>()(AxSelectTable);
